package com.aos.erp.manager.service.impl;

import com.aos.erp.common.bean.PageBean;
import com.aos.erp.common.dao.mapper.Condition;
import com.aos.erp.common.exception.BizException;
import com.aos.erp.common.utils.DateUtils;
import com.aos.erp.manager.enums.review.ExportFileType;
import com.aos.erp.manager.enums.review.ImportExportType;
import com.aos.erp.manager.enums.review.StatisticsDataType;
import com.aos.erp.manager.mapper.review.*;
import com.aos.erp.manager.model.review.*;
import com.aos.erp.manager.model.review.vo.CheckResultFailVo;
import com.aos.erp.manager.model.review.vo.ReviewConditionVo;
import com.aos.erp.manager.remote.DriverSchoolService;
import com.aos.erp.manager.remote.GovService;
import com.aos.erp.manager.remote.model.GovExRegisterTask;
import com.aos.erp.manager.remote.model.Region;
import com.aos.erp.manager.remote.model.StudentFileInfo;
import com.aos.erp.manager.remote.model.StudentInfo;
import com.aos.erp.manager.remote.model.vo.ExportStudentConditionVo;
import com.aos.erp.manager.remote.model.vo.ExportStudentForGovConditionVo;
import com.aos.erp.manager.service.StudentReviewService;
import com.aos.erp.manager.service.mq.SenderSubmitted;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class StudentReviewServiceImpl extends ServiceImpl<ExportRecordMapper, ExportRecord> implements StudentReviewService {

    /**
     * 驾校服务
     */
    @Resource
    private DriverSchoolService driverSchoolService;

    /**
     * GOV服务
     */
    @Resource
    private GovService govService;

    @Resource
    private CheckResultImportRecordMapper checkResultImportRecordMapper;

    @Resource
    private CheckResultImportRecordDetailMapper checkResultImportRecordDetailMapper;

    @Resource
    private ExportRecordDetailMapper exportRecordDetailMapper;

    @Resource
    private ExportRecordStatisticsMapper exportRecordStatisticsMapper;

    @Resource
    private SenderSubmitted senderSubmitted;

    @Override
    public List<StudentInfo> saveAndGetExportData(ExportStudentConditionVo conditionVo, String optUser) throws Exception {

        // 获取城市信息
        List<Region> regionList = driverSchoolService.queryCityList(conditionVo.getCityCode());
        if(regionList == null || regionList.size() == 0) {
            throw  new BizException("无效的城市");
        }
        Region cityData = regionList.get(0);

        // 获取要导出的数据
//        conditionVo.setCityId(cityData.getId())
        conditionVo.setPageSize(1);
        List<StudentInfo> studentInfoList = pageQueryExportData(conditionVo);

        // 保存导出记录
        Date nowDate = new Date();
        ExportRecord exportRecord = new ExportRecord();
        exportRecord.setSerialNumber(DateUtils.getXXTimeString());
        exportRecord.setDataCount(studentInfoList.size());
        exportRecord.setOptCityCode(cityData.getCode());
        exportRecord.setOptProvinceCode(cityData.getParentCode());
        exportRecord.setOptCityName(cityData.getParentName() + "-" + cityData.getName());
        exportRecord.setExportTime(nowDate);
        exportRecord.setOptUser(optUser);
        baseMapper.insert(exportRecord);

        int fingerprintCount = 0;    // 指纹数量
        int oldDrivingLicenceCount = 0;    // 原驾驶证数量
        int certificatePhotosCount = 0;    // 制证照数量
        int signDataCount = 0;    // 签字数据数量

        // 保存记录明细
        for (StudentInfo studentData : studentInfoList) {
            ExportRecordDetail exportRecordDetail = new ExportRecordDetail();
            exportRecordDetail.setSerialNumber(exportRecord.getSerialNumber()); // 流水号
            exportRecordDetail.setRecordId(exportRecord.getId());   // 导出记录ID
            exportRecordDetail.setDrivingLicenseType(studentData.getCarName()); //  驾照类型
            exportRecordDetail.setIdNo(studentData.getCertificatesNumber());    //  证件号码
            exportRecordDetail.setStudentName(studentData.getName());       //  学员姓名
            exportRecordDetail.setOptType(ImportExportType.exp);
            exportRecordDetail.setExportTime(nowDate);      //  导出时间
            if(studentData.getListStudentPicture() == null || studentData.getListStudentPicture().size() == 0) {
                // 无文件
                exportRecordDetail.setFileType(ExportFileType.normal);
                exportRecordDetailMapper.insert(exportRecordDetail);
            } else {
                // 有文件
                for (StudentFileInfo studentFileInfo : studentData.getListStudentPicture()) {
                    ExportRecordDetail exportRecordDetailForFile = new ExportRecordDetail();
                    BeanUtils.copyProperties(exportRecordDetail, exportRecordDetailForFile);
                    exportRecordDetailForFile.setId(0);
                    exportRecordDetailForFile.setFileType(studentFileInfo.getType());
                    exportRecordDetailMapper.insert(exportRecordDetailForFile);

                    if(studentFileInfo.getType() == ExportFileType.zw) {
                        // 指纹统计
                        fingerprintCount++;
                    } else if(studentFileInfo.getType() == ExportFileType.zjzo) {
                        // 证件照统计
                        certificatePhotosCount++;
                    } else if(studentFileInfo.getType() == ExportFileType.mqb || studentFileInfo.getType() == ExportFileType.zcbmqz) {
                        // 签字数据统计：互联网面签协议、注册表面签照
                        signDataCount++;
                    } else if(studentFileInfo.getType() == ExportFileType.ljz) {
                        // 原驾驶证统计
                        certificatePhotosCount++;
                    }
                }
            }
        }

        // 保存统计信息
        ExportRecordStatistics exportRecordStatistics = new ExportRecordStatistics();
        exportRecordStatistics.setCertificatePhotosCount(certificatePhotosCount);
        exportRecordStatistics.setFingerprintCount(fingerprintCount);
        exportRecordStatistics.setOldDrivingLicenceCount(oldDrivingLicenceCount);
        exportRecordStatistics.setPaperlessListCount(studentInfoList.size());
        exportRecordStatistics.setRecordId(exportRecord.getId());
        exportRecordStatistics.setSignDataCount(signDataCount);
        exportRecordStatistics.setStudentCount(studentInfoList.size());
        exportRecordStatistics.setOptType(ImportExportType.exp);
        exportRecordStatistics.setDataType(StatisticsDataType.success);

        exportRecordStatisticsMapper.insert(exportRecordStatistics);
        return studentInfoList;
    }

    /**
     * 获取要导出的数据
     * @param conditionVo
     * @return
     */
    private List<StudentInfo> pageQueryExportData(ExportStudentConditionVo conditionVo) {
        List<StudentInfo> exportList = new ArrayList<>();
//        PageBean<StudentInfo> pageBean = getPageBeanDemo(conditionVo);
        // 从Gov服务查询出要导出的学员基本信息
        ExportStudentForGovConditionVo govConditionVo = new ExportStudentForGovConditionVo();
        govConditionVo.setCityCode(conditionVo.getCityCode());
        govConditionVo.setSchoolId(conditionVo.getDriverSchoolId());
        govConditionVo.setText(conditionVo.getSearchKey());
        govConditionVo.setType(conditionVo.getTimeType());
        govConditionVo.setStartTime(conditionVo.getFromDate());
        govConditionVo.setEndTime(conditionVo.getToDate());
        govConditionVo.setPageIndex(conditionVo.getPageIndex());
        govConditionVo.setPageSize(conditionVo.getPageSize());
        PageBean<GovExRegisterTask> pageBean = govService.queryStudentList(govConditionVo);

        // 封装要导出的学员Id列表
        List<Long> studentIdList = new ArrayList<>();
        for (GovExRegisterTask dataItem : pageBean.getRecords()) {
            studentIdList.add(dataItem.getStudentId());
        }

        ExportStudentConditionVo dsCondition = new ExportStudentConditionVo();
        dsCondition.setPageIndex(1);
        dsCondition.setPageSize(conditionVo.getPageSize());
        dsCondition.setStudentId(studentIdList);

        // 调用驾校服务查询要导出的学员详细信息
        List<StudentInfo> studentList = driverSchoolService.queryExportStudentList(dsCondition);
        exportList.addAll(studentList);

        // 检测是否还有数据
        if(pageBean.hasNext()) {
            conditionVo.setPageIndex(conditionVo.getPageIndex() + 1);
            List<StudentInfo> nextPageList = pageQueryExportData(conditionVo);
            exportList.addAll(nextPageList);
        }
        return exportList;
    }

    @Override
    public void saveImportData(List<List<String>> importData, long recordId) throws Exception {

        // 获取城市信息
        ExportRecord exportRecord = baseMapper.selectById(recordId);
        if(exportRecord == null || exportRecord.getId() == 0) {
            throw  new BizException("无效的导出记录");
        }

        // 更新导出记录导入时间
        baseMapper.updateForBackWrite(recordId);

        List<ExportRecordDetail> recordDetailList = transferToImportDetailList(importData);

        // 更新明细记录的导入时间
        exportRecordDetailMapper.updateForBackWrite(exportRecord.getId());

        // 统计导出结果
        statisticsExportResult(recordId, recordDetailList);
    }

    private void statisticsExportResult(long recordId, List<ExportRecordDetail> recordDetailList) {

        // 统计数据
        int fingerprintSuccessCount = 0;    // 指纹数量
        int fingerprintFailCount = 0;       // 指纹数量
        int oldDrivingLicenceSuccessCount = 0;    // 原驾驶证数量
        int oldDrivingLicenceFailCount = 0;       // 原驾驶证数量
        int certificatePhotosSuccessCount = 0;    // 制证照数量
        int certificatePhotosFailCount = 0;       // 制证照数量
        int signDataSuccessCount = 0;    // 签字数据数量
        int signDataFailCount = 0;       // 签字数据数量
        List<String> successStudentList = new ArrayList<>();   // 成功学员
        List<String> failStudentList = new ArrayList<>();   // 失败学员


        // 更新导入时间
        for (ExportRecordDetail exportRecordDetail : recordDetailList) {
            if("成功".equals(exportRecordDetail.getResult())) {
                if(!successStudentList.contains(exportRecordDetail.getIdNo())) {
                    successStudentList.add(exportRecordDetail.getIdNo());
                }
                if(exportRecordDetail.getFileType() == ExportFileType.zw) {
                    // 指纹统计
                    fingerprintSuccessCount++;
                } else if(exportRecordDetail.getFileType() == ExportFileType.zjzo) {
                    // 证件照统计
                    certificatePhotosSuccessCount++;
                } else if(exportRecordDetail.getFileType() == ExportFileType.mqb || exportRecordDetail.getFileType() == ExportFileType.zcbmqz) {
                    // 签字数据统计：互联网面签协议、注册表面签照
                    signDataSuccessCount++;
                } else if(exportRecordDetail.getFileType() == ExportFileType.ljz) {
                    // 原驾驶证统计
                    certificatePhotosSuccessCount++;
                }

            } else {
                if(!failStudentList.contains(exportRecordDetail.getIdNo())) {
                    failStudentList.add(exportRecordDetail.getIdNo());
                }
                if(exportRecordDetail.getFileType() == ExportFileType.zw) {
                    // 指纹统计
                    fingerprintFailCount++;
                } else if(exportRecordDetail.getFileType() == ExportFileType.zjzo) {
                    // 证件照统计
                    certificatePhotosFailCount++;
                } else if(exportRecordDetail.getFileType() == ExportFileType.mqb || exportRecordDetail.getFileType() == ExportFileType.zcbmqz) {
                    // 签字数据统计：互联网面签协议、注册表面签照
                    signDataFailCount++;
                } else if(exportRecordDetail.getFileType() == ExportFileType.ljz) {
                    // 原驾驶证统计
                    certificatePhotosFailCount++;
                }
            }
        }

        // 发送成功的学员MQ消息
        senderSubmitted.sendSubmit(successStudentList);

        // 保存统计信息
        ExportRecordStatistics exportRecordStatisticsSuccess = new ExportRecordStatistics();
        exportRecordStatisticsSuccess.setCertificatePhotosCount(certificatePhotosSuccessCount);
        exportRecordStatisticsSuccess.setFingerprintCount(fingerprintSuccessCount);
        exportRecordStatisticsSuccess.setOldDrivingLicenceCount(oldDrivingLicenceSuccessCount);
        exportRecordStatisticsSuccess.setPaperlessListCount(successStudentList.size());
        exportRecordStatisticsSuccess.setRecordId(recordId);
        exportRecordStatisticsSuccess.setSignDataCount(signDataSuccessCount);
        exportRecordStatisticsSuccess.setStudentCount(successStudentList.size());
        exportRecordStatisticsSuccess.setOptType(ImportExportType.imp);
        exportRecordStatisticsSuccess.setDataType(StatisticsDataType.success);
        exportRecordStatisticsMapper.insert(exportRecordStatisticsSuccess);

        ExportRecordStatistics exportRecordStatistics = new ExportRecordStatistics();
        exportRecordStatistics.setCertificatePhotosCount(certificatePhotosFailCount);
        exportRecordStatistics.setFingerprintCount(fingerprintFailCount);
        exportRecordStatistics.setOldDrivingLicenceCount(oldDrivingLicenceFailCount);
        exportRecordStatistics.setPaperlessListCount(failStudentList.size());
        exportRecordStatistics.setRecordId(recordId);
        exportRecordStatistics.setSignDataCount(signDataFailCount);
        exportRecordStatistics.setStudentCount(failStudentList.size());
        exportRecordStatistics.setOptType(ImportExportType.imp);
        exportRecordStatistics.setDataType(StatisticsDataType.fail);
        exportRecordStatisticsMapper.insert(exportRecordStatistics);
    }


    @Override
    public void deleteExportRecord(String ids) throws Exception {

        if(ids.length() == 0) {
            throw new BizException("记录ID不能为空");
        }
        baseMapper.deleteRecord(ids);
    }

    @Override
    public PageBean<ExportRecord> findExportRecordByPage(ReviewConditionVo conditionVo) {
        Page<ExportRecord> page = new Page<ExportRecord>(conditionVo.getPageIndex(), conditionVo.getPageSize());
        List<ExportRecord> noticeInfoList = baseMapper.pageRecordList(page, conditionVo);
        page.setRecords(noticeInfoList);

        PageBean<ExportRecord> bean = new PageBean<ExportRecord>(page.getCurrent(), page.getSize(), page.getTotal());
        bean.setOptimizeCountSql(page.optimizeCountSql());
        bean.setAscs(page.ascs());
        bean.setDescs(page.descs());
        bean.setRecords(page.getRecords());
        bean.condition();

        return bean;
    }

    @Override
    public PageBean<ExportRecordDetail> findExportDetailByPage(ReviewConditionVo conditionVo) {
        Page<ExportRecordDetail> page = new Page<ExportRecordDetail>(conditionVo.getPageIndex(), conditionVo.getPageSize());
        List<ExportRecordDetail> noticeInfoList = exportRecordDetailMapper.pageRecordList(page, conditionVo);
        page.setRecords(noticeInfoList);

        PageBean<ExportRecordDetail> bean = new PageBean<ExportRecordDetail>(page.getCurrent(), page.getSize(), page.getTotal());
        bean.setOptimizeCountSql(page.optimizeCountSql());
        bean.setAscs(page.ascs());
        bean.setDescs(page.descs());
        bean.setRecords(page.getRecords());
        bean.condition();

        return bean;
    }

    @Override
    public List<ExportRecordStatistics> getExportStatistics(long recordId) {
        Condition condition = new Condition(ExportRecordStatistics.class);
        condition.eqFiled("recordId", recordId);
        return exportRecordStatisticsMapper.selectList(condition.getWrapper());
    }


    @Override
    public void saveImportCheckResultData(List<List<String>> importData, String cityCode, String optUser) throws Exception {

        // 获取城市信息
        List<Region> regionList = driverSchoolService.queryCityList(cityCode);
        if(regionList == null || regionList.size() == 0) {
            throw  new BizException("无效的城市");
        }
        Region cityData = regionList.get(0);

        List<CheckResultImportRecordDetail> recordDetailList = transferToCheckResultImportDetailList(importData);

        // 保存导入记录
        Date nowDate = new Date();
        CheckResultImportRecord importRecord = new CheckResultImportRecord();
        importRecord.setSerialNumber(DateUtils.getXXTimeString());
        importRecord.setDataCount(importData.size());
        importRecord.setOptProvinceCode(cityData.getParentCode());
        importRecord.setOptCityCode(cityData.getCode());
        importRecord.setOptCityName(cityData.getParentName() + "-" + cityData.getName());
        importRecord.setOptTime(nowDate);
        importRecord.setOptUser(optUser);

        checkResultImportRecordMapper.insert(importRecord);

        List<String> successStudentList = new ArrayList<>();
//        List<String> failStudentList = new ArrayList<>();
        List<CheckResultFailVo> failStudentInfoList = new ArrayList<>();

        // 保存记录明细
        for (CheckResultImportRecordDetail checkResultImportRecordDetail : recordDetailList) {
            checkResultImportRecordDetail.setSerialNumber(importRecord.getSerialNumber());
            checkResultImportRecordDetail.setRecordId(importRecord.getId());
            if("办结".equals(checkResultImportRecordDetail.getProcessingResults())) {
                successStudentList.add(checkResultImportRecordDetail.getIdNo());
            } else {
//                failStudentList.add(checkResultImportRecordDetail.getIdNo());
                CheckResultFailVo checkResultFailVo = new CheckResultFailVo();
                BeanUtils.copyProperties(checkResultImportRecordDetail, checkResultFailVo);
                failStudentInfoList.add(checkResultFailVo);
            }
            checkResultImportRecordDetailMapper.insert(checkResultImportRecordDetail);
        }

        if(successStudentList.size() > 0) {
            // 发送审核结果处理消息(成功)
            senderSubmitted.sendSuccess(successStudentList);
        }
        if(failStudentInfoList.size() > 0) {
            // 发送审核结果处理消息(失败)
            senderSubmitted.sendFail(failStudentInfoList);
        }
    }

    @Override
    public void deleteImportRecord(String ids) throws Exception {

        if(ids.length() == 0) {
            throw new BizException("记录ID不能为空");
        }
        checkResultImportRecordMapper.deleteRecord(ids);
    }

    @Override
    public PageBean<CheckResultImportRecord> findImportRecordByPage(ReviewConditionVo conditionVo) {
        Page<CheckResultImportRecord> page = new Page<CheckResultImportRecord>(conditionVo.getPageIndex(), conditionVo.getPageSize());
        List<CheckResultImportRecord> noticeInfoList = checkResultImportRecordMapper.pageRecordList(page, conditionVo);
        page.setRecords(noticeInfoList);

        PageBean<CheckResultImportRecord> bean = new PageBean<CheckResultImportRecord>(page.getCurrent(), page.getSize(), page.getTotal());
        bean.setOptimizeCountSql(page.optimizeCountSql());
        bean.setAscs(page.ascs());
        bean.setDescs(page.descs());
        bean.setRecords(page.getRecords());
        bean.condition();

        return bean;
    }


    @Override
    public PageBean<CheckResultImportRecordDetail> findImportDetailByPage(ReviewConditionVo conditionVo) {
        Page<CheckResultImportRecordDetail> page = new Page<CheckResultImportRecordDetail>(conditionVo.getPageIndex(), conditionVo.getPageSize());
        List<CheckResultImportRecordDetail> noticeInfoList = checkResultImportRecordDetailMapper.pageRecordList(page, conditionVo);
        page.setRecords(noticeInfoList);

        PageBean<CheckResultImportRecordDetail> bean = new PageBean<CheckResultImportRecordDetail>(page.getCurrent(), page.getSize(), page.getTotal());
        bean.setOptimizeCountSql(page.optimizeCountSql());
        bean.setAscs(page.ascs());
        bean.setDescs(page.descs());
        bean.setRecords(page.getRecords());
        bean.condition();

        return bean;
    }


    private List<ExportRecordDetail> transferToImportDetailList(List<List<String>> importData){

        List<ExportRecordDetail> exportRecordDetailList = new ArrayList<>();
        for (List<String> importDataItem : importData) {
            ExportRecordDetail exportRecordDetail = new ExportRecordDetail();
            exportRecordDetail.setStudentName(importDataItem.get(0));
            exportRecordDetail.setIdNo(importDataItem.get(1));
            exportRecordDetail.setFileType(ExportFileType.getFileType(importDataItem.get(2)));
            exportRecordDetail.setResult(importDataItem.get(3));
            exportRecordDetailList.add(exportRecordDetail);
        }
        return exportRecordDetailList;
    }

    private List<CheckResultImportRecordDetail> transferToCheckResultImportDetailList(List<List<String>> importData){

        List<CheckResultImportRecordDetail> checkResultImportRecordDetailList = new ArrayList<>();
        for (List<String> importDataItem : importData) {
            CheckResultImportRecordDetail checkResultImportRecordDetail = new CheckResultImportRecordDetail();
            checkResultImportRecordDetail.setStudentName(importDataItem.get(3));
            checkResultImportRecordDetail.setIdNo(importDataItem.get(4));
            checkResultImportRecordDetail.setCarType(importDataItem.get(5));
            checkResultImportRecordDetail.setDsName(importDataItem.get(6));
            checkResultImportRecordDetail.setBizType(importDataItem.get(7));
            checkResultImportRecordDetail.setHasPaperless(importDataItem.get(8));
            checkResultImportRecordDetail.setHasCertificatePhotos(importDataItem.get(9));
            checkResultImportRecordDetail.setHasFingerprint(importDataItem.get(10));
            checkResultImportRecordDetail.setHasCertificatePhotosBig(importDataItem.get(11));
            checkResultImportRecordDetail.setHasOldDrivingLicense(importDataItem.get(12));
            checkResultImportRecordDetail.setProcessingResults(importDataItem.get(13));
            checkResultImportRecordDetail.setFeedbackResult(importDataItem.get(14));
            checkResultImportRecordDetail.setApplyTime(DateUtils.toDate(importDataItem.get(15)));
            checkResultImportRecordDetail.setProcessingTime(DateUtils.toDate(importDataItem.get(16)));
            checkResultImportRecordDetail.setManagerDepartment(importDataItem.get(17));
            checkResultImportRecordDetailList.add(checkResultImportRecordDetail);
        }
        return checkResultImportRecordDetailList;
    }
}
